const { goodsApi } = require('../../services/api')

Page({
  data: {
    goodsId: null,
    goodsInfo: null,
    isCollected: false
  },

  onLoad: function(options) {
    this.setData({
      goodsId: options.id
    })
    this.loadGoodsDetail()
  },

  // 加载商品详情
  loadGoodsDetail: async function() {
    try {
      const res = await goodsApi.getGoodsDetail(this.data.goodsId)
      this.setData({
        goodsInfo: res.data
      })
    } catch (err) {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    }
  },

  // 收藏/取消收藏
  toggleCollect: async function() {
    try {
      await goodsApi.toggleCollect(this.data.goodsId)
      this.setData({
        isCollected: !this.data.isCollected
      })
    } catch (err) {
      wx.showToast({
        title: err.message,
        icon: 'none'
      })
    }
  }

  // 联系卖家
  contactSeller: function() {
    const { sellerId } = this.data.goodsInfo
    wx.navigateTo({
      url: `/pages/chat-detail/chat-detail?userId=${sellerId}`
    })
  }
})